package com.supergzt.service.impl;


import com.alibaba.fastjson2.TypeReference;
import com.supergzt.constant.SecurityConstants;
import com.supergzt.constant.TokenConstants;
import com.supergzt.entity.base.LoginUser;
import com.supergzt.service.RedissonService;
import com.supergzt.service.TokenService;
import com.supergzt.utils.JwtUtils;
import com.supergzt.utils.KeyUtils;
import com.supergzt.utils.SecurityUtils;
import com.supergzt.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 张钧
 * @Description
 * @create 2022-09-25 21:45
 */
@Service
public class TokenServiceImpl implements TokenService {

	@Resource
	private RedissonService redissonService;

	@Override
	public String createToken(LoginUser loginUser) {
		String token = UUID.randomUUID().toString();
		Long userId = loginUser.getUser().getUserId();
		String userName = loginUser.getUser().getName();
		loginUser.setToken(token);
		refreshToken(loginUser);
		// Jwt存储信息
		Map<String, Object> claimsMap = new HashMap<>(3);
		claimsMap.put(SecurityConstants.USER_KEY, token);
		claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
		claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
		return JwtUtils.createToken(claimsMap);
	}

	/**
	 * 获取用户身份信息
	 *
	 * @return 用户信息
	 */
	@Override
	public LoginUser getLoginUser(HttpServletRequest request) {
		// 获取请求携带的令牌
		String token = SecurityUtils.getToken(request);
		return getLoginUser(token);
	}

	/**
	 * 刷新令牌有效期
	 *
	 * @param loginUser 登录信息
	 */
	@Override
	public void refreshToken(LoginUser loginUser) {
		loginUser.setLoginTime(System.currentTimeMillis());
		loginUser.setExpireTime(loginUser.getLoginTime() + TokenConstants.EXPIRE_TIME);
		this.forceLogout(loginUser.getUser().getUserId());
		// 根据uuid将loginUser缓存
		redissonService.setString(KeyUtils.createToken(loginUser.getUser().getUserId().toString(),loginUser.getToken()),loginUser,TokenConstants.EXPIRE_TIME);
	}

	/**
	 * 获取用户身份信息
	 *
	 * @return 用户信息
	 */
	@Override
	public LoginUser getLoginUser(String token) {
		LoginUser user = null;
		if (StringUtils.isNotNull(token)) {
			String userId = JwtUtils.getUserId(token);
			String userKey = JwtUtils.getUserKey(token);
			user = redissonService.getString(KeyUtils.createToken(userId, userKey), new TypeReference<>() {});
		}
		return user;
	}

	/**
	 * 设置用户身份信息
	 */
	@Override
	public void setLoginUser(LoginUser loginUser) {
		if (StringUtils.isNotNull(loginUser) && StringUtils.isNotNull(loginUser.getToken())) {
			refreshToken(loginUser);
		}
	}

	/**
	 * 删除用户缓存信息
	 */
	@Override
	public void deleteLoginUser(String token) {
		if (StringUtils.isNotNull(token)) {
			String userId = JwtUtils.getUserId(token);
			String userKey = JwtUtils.getUserKey(token);
			redissonService.removeString(KeyUtils.createToken(userId,userKey));
		}
	}

	/**
	 * 验证令牌有效期，相差不足120分钟，自动刷新缓存
	 *
	 * @param loginUser
	 */
	@Override
	public void verifyToken(LoginUser loginUser) {
		long expireTime = loginUser.getExpireTime();
		long currentTime = System.currentTimeMillis();
		if (expireTime - currentTime <= 1) {
			refreshToken(loginUser);
		}
	}

	@Override
	public void logout(HttpServletRequest request) {
		deleteLoginUser(SecurityUtils.getToken(request));
	}

	/**
	 * @param userId
	 */
	@Override
	public void forceLogout(Long userId) {
		String scanKey = KeyUtils.createScanKey(TokenConstants.ACCESS_TOKEN,userId);
		List<String> users = redissonService.scanString(scanKey);
		redissonService.removeStringList(users);
	}
}
